package com.meida.paotui.bus.provider.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.egzosn.pay.common.bean.PayOrder;
import com.egzosn.pay.common.http.UriVariables;
import com.meida.common.mybatis.base.service.impl.BaseServiceImpl;
import com.meida.common.mybatis.entity.EntityMap;
import com.meida.common.mybatis.model.PageModel;
import com.meida.common.mybatis.model.ResultBody;
import com.meida.common.mybatis.query.CriteriaQuery;
import com.meida.common.security.OpenHelper;
import com.meida.common.utils.ApiAssert;
import com.meida.common.utils.FlymeUtils;
import com.meida.module.marketing.provider.service.CouponUserService;
import com.meida.module.pay.client.entity.PayConfig;
import com.meida.module.pay.client.enums.PayType;
import com.meida.module.pay.provider.response.PayResponse;
import com.meida.module.pay.provider.service.PayConfigService;
import com.meida.paotui.bus.client.entity.BusGoodsorder;
import com.meida.paotui.bus.client.entity.BusWeightprice;
import com.meida.paotui.bus.provider.mapper.BusGoodsorderMapper;
import com.meida.paotui.bus.provider.service.BusGoodsorderService;
import com.meida.paotui.bus.provider.service.BusWeightpriceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 订单表 实现类
 *
 * @author flyme
 * @date 2019-11-12
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class BusGoodsorderServiceImpl extends BaseServiceImpl<BusGoodsorderMapper, BusGoodsorder> implements BusGoodsorderService {

    @Autowired
    private BusWeightpriceService weightpriceService;
    @Autowired
    private CouponUserService couponuserService;
    @Autowired
    private PayConfigService payConfigService;
    @Autowired
    private BusGoodsorderMapper busGoodsorderMapper;


    /**
     * 缓存
     */
    private final static Map<Long, PayResponse> payResponses = new HashMap();


    @Override
    public Double getCommission(Double distance, Double weight, Long couponId,Double tip) {
        BigDecimal  voucherSum=null;
      if(ObjectUtils.isNotEmpty(couponId)){
          EntityMap map=couponuserService.getCoupon(couponId);
          //折扣
          voucherSum = map.get("couponPrice");
      }
      Double start_d_price=0.00;
      Double start_w_price=0.00;
      Double unit_w_price=0.00;
      Double unit_d_price=0.00;
      Double total_distance=0.00;
      Double total_weight=0.00;
      Double total_sum=0.00;
          List<BusWeightprice> mapalist=weightpriceService.list();
          for (BusWeightprice l : mapalist) {
              Double startDistance=l.getStartDistance().doubleValue();
              Double endDistance=l.getDistancePrice().doubleValue();
              distance=distance/1000;
              if(distance>startDistance&&distance<=endDistance){
                  start_d_price=l.getStartDistance().doubleValue();
                  unit_d_price=l.getUnitDistance().doubleValue();
                  total_distance=(endDistance-distance)*unit_d_price+start_d_price;
              }
              Double startWeight=l.getStartWeight().doubleValue();
              Double endWeight=l.getEndWeight().doubleValue();
              if(weight>startWeight&&weight<=endWeight){
                  start_w_price=l.getWeightprice().doubleValue();
                  unit_w_price=l.getUnitWeight().doubleValue();
                  total_weight=(endWeight-weight)*unit_w_price+start_w_price;
              }
          }
          total_sum=total_distance+total_weight;
          //算出折扣后的价格
           if(ObjectUtils.isNotEmpty(voucherSum)){
               total_sum=total_sum*(voucherSum.doubleValue()/10);
           }
           if(FlymeUtils.isNotEmpty(tip)){
               total_sum=total_sum+tip;

           }
          return total_sum;
    }

    @Override
    public ResultBody getOrderList(PageModel model,String status,String isInvoice) {
        CriteriaQuery cq = new CriteriaQuery(model, BusGoodsorder.class);
        cq.select(BusGoodsorder.class, "*");
        cq.eq(BusGoodsorder.class,"userId", OpenHelper.getUserId());
        if(FlymeUtils.isNotEmpty(status)) {
            cq.eq(BusGoodsorder.class, "status", status);
        }
        if(FlymeUtils.isNotEmpty(isInvoice)) {
            cq.eq(BusGoodsorder.class, "isInvoice", isInvoice);
        }
        cq.orderByDesc("createTime");
        return basePageList(cq);
    }
    /**
     * @param orderId
     * @param invoiceId
     * @return
     */
    @Override
    public Boolean updateInvoiceId(Long GoodsOrderId, Long invoiceId) {
        UpdateWrapper uw = new UpdateWrapper();
        uw.set(true, "invoiceId", invoiceId);
        uw.eq("goodsOrderId", GoodsOrderId);
        return update(uw);
    }

    @Override
    public ResultBody sendUserList(PageModel model) {
        CriteriaQuery cq = new CriteriaQuery(model, BusGoodsorder.class);
        cq.select(BusGoodsorder.class, "*");
        cq.eq(BusGoodsorder.class,"sendUserInfoId", OpenHelper.getUserId());
        cq.eq(BusGoodsorder.class,"status");
        return basePageList(cq);
    }


    @Override
    public EntityMap findGoodsOrderCount(Long sendUserInfoId,String  startDate,String  endDate) {
        Map map=new HashMap();
        map.put("sendUserInfoId",sendUserInfoId);
        map.put("startDate",startDate);
        map.put("endDate",endDate);
        return  busGoodsorderMapper.findGoodsOrderCount(map);
    }

    @Override
    public EntityMap findCancelOrderCount(Long sendUserInfoId,String  startDate,String  endDate) {
        Map map=new HashMap();
        map.put("sendUserInfoId",sendUserInfoId);
        map.put("startDate",startDate);
        map.put("endDate",endDate);
        return busGoodsorderMapper.findCancelOrderCount(map);
    }

    @Override
    public List<EntityMap> findmothbils(Long sendUserInfoId) {
        Map map=new HashMap();
        map.put("sendUserInfoId",sendUserInfoId);
        return busGoodsorderMapper.findmothbils(map);
    }

    @Override
    public int findCtnDataByDistance(Double lng, Double lat, String distance,String deliveryTime,String commission) {
        Map map=new HashMap();
        map.put("lng",lng);
        map.put("lat",lat);
        map.put("distance",distance);
        if(FlymeUtils.isNotEmpty(deliveryTime)){
            if(deliveryTime.equals("0")) {
                map.put("deliveryTimeasc","0");
            }else if(deliveryTime.equals("1")){
                map.put("deliveryTimedesc","1");
            }
        }
        if(FlymeUtils.isNotEmpty(commission)){
            if(commission.equals("0")) {
                map.put("commissionasc","0");
            }else if(commission.equals("1")){
                map.put("commissiondesc","1");
            }
        }
        return busGoodsorderMapper.findCtnDataByDistance(map);
    }

    @Override
    public List<EntityMap> findListDataByDistance(Double lng, Double lat, Double distance,String deliveryTime ,String commission,PageModel pageModel) {
        Map map=new HashMap();
        map.put("lng",lng);
        map.put("lat",lat);
        map.put("distance",distance);
        map.put("page",(pageModel.getPage()-1)*pageModel.getLimit());
        map.put("limit",pageModel.getLimit());

        if(FlymeUtils.isNotEmpty(deliveryTime)){
           if(deliveryTime.equals("0")) {
               map.put("deliveryTimeasc","0");
           }else if(deliveryTime.equals("1")){
               map.put("deliveryTimedesc","1");
           }
        }
        if(FlymeUtils.isNotEmpty(commission)){
            if(commission.equals("0")) {
                map.put("commissionasc","0");
            }else if(commission.equals("1")){
                map.put("commissiondesc","1");
            }
        }
        if(FlymeUtils.isNotEmpty(deliveryTime)||FlymeUtils.isNotEmpty(commission)){
            map.put("orderflag","1");
        }
        return busGoodsorderMapper.findListDataByDistance(map);
    }




    /**
     * 获取支付响应
     *
     * @param id 账户id
     * @return 支付响应
     */
    public PayResponse getPayResponse(Long id) {

        PayResponse payResponse = payResponses.get(id);
        if (payResponse == null) {
            PayConfig apyAccount = payConfigService.getById(id);
            ApiAssert.isNotEmpty("支付账户不存在", apyAccount);
            payResponse = new PayResponse();
            spring.autowireBean(payResponse);
            payResponse.init(apyAccount,null);
            payResponses.put(id, payResponse);
        }
        return payResponse;
    }

    /******微信支付宝支付***/
    public Object AliWEI(String  payType, BusGoodsorder goodsorder) {
        PayOrder payOrder = new PayOrder("订单支付", "订单支付", goodsorder.getRealPaySum(), String.valueOf(goodsorder.getGoodsOrderId()));
        PayResponse payResponse = null;
        EntityMap extra = new EntityMap();
        if (payType.equals(PayType.aliPay.name())) {
            payResponse = getPayResponse(1L);
            extra.put("payId", 1L);
        } else {
            payResponse = getPayResponse(3L);
            extra.put("payId", 3L);
        }

        Object payInfo = null;
        payOrder.setTransactionType(PayType.valueOf(payType).getTransactionType("APP"));
        if (payType.equals(PayType.aliPay.name())) {
            System.out.println("--------------------------------"+payResponse.getService());
            payInfo = UriVariables.getMapToParameters(payResponse.getService().orderInfo(payOrder));
        }
        if (payType.equals(PayType.wxPay.name())) {
            Map<String, Object> map = payResponse.getService().orderInfo(payOrder);
            payInfo = JSONUtil.toJsonStr(map);
        }
        extra.put("outTradeNo", goodsorder.getGoodsOrderId());
        return payInfo;
    }
}
